
package com.lwl.java8.chapter7;

import java.util.concurrent.RecursiveTask;

public class ForkJoinSumCalculator extends RecursiveTask<Long> {

	private static final long serialVersionUID = 1L;

	// 要求和的数组
	private final long[] numbers;
	// 子任务处理的数组的起始和终止位置
	private final int start;
	private final int end;

	// 不再将任务分解为子任务的数组大小
	public static final long threshold = 10_000;

	/**
	 * 公共构造函数用于创建主任务
	 */
	public ForkJoinSumCalculator(long[] numbers) {
		this(numbers, 0, numbers.length);
	}

	/*
	 * 私有构造函数用于以递归方式为主任务创建子任务
	 */
	private ForkJoinSumCalculator(long[] numbers, int start, int end) {
		this.numbers = numbers;
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		int length = end - start;
		if (length <= threshold) {
			return computeSequentially();
		}
		ForkJoinSumCalculator leftTask = new ForkJoinSumCalculator(numbers, start, start + length / 2);
		leftTask.fork();
		
		ForkJoinSumCalculator rightTask = new ForkJoinSumCalculator(numbers, start + length / 2, end);
		Long rightResult = rightTask.compute();
		
		Long leftResult = leftTask.join();
		return leftResult + rightResult;
	}

	/**
	 * 求和
	 * @return
	 */
	private long computeSequentially() {
		long sum = 0;
		for (int i = start; i < end; i++) {
			sum += numbers[i];
		}
		return sum;
	}

	
}
